package logic

import (
	"context"
	"errors"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRealnameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRealnameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRealnameLogic {
	return &UserRealnameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRealnameLogic) UserRealname(in *user.UserRealnameRequest) (*user.UserRealnameResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var ur models.UserRealname
	ur.UserId = in.UserId
	ur.Realname = in.Realname
	ur.Idcard = in.Idcard
	if err = ur.FindRealnameByUserId(); err != nil {
		logx.Error("查询用户实名信息失败", err)
		return nil, err
	}
	if ur.ID != 0 {
		logx.Error("用户已实名", err)
		return nil, errors.New("用户已实名")
	}
	if !pkg.Realname(ur.Idcard, ur.Realname) {
		logx.Error("用户实名失败", err)
		return nil, errors.New("用户实名失败")
	}
	if err = ur.Create(); err != nil {
		logx.Error("保存用户实名信息失败", err)
		return nil, err
	}
	return &user.UserRealnameResponse{}, nil
}
